﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Runtime;

namespace LprMiddleWare.HangWang
{


    public class HanWangController : IDisposable
    {
        private HWCtrlLinkCallback _callback;

        public event EventHandler<ControlEventArgs> StatusReport;

        public void OnStatusReport(ControlEventArgs e)
        {
            EventHandler<ControlEventArgs> handler = StatusReport;
            if (handler != null) handler(this, e);
        }


        public HanWangController()
        {
            _callback = CallBack;
        }

        public void Connect(string ipAddress)
        {
            var ip = System.Net.IPAddress.Parse(ipAddress);
            var parm = new tagHWCtrlLinkParam();
            var iplong = (int) Util.ConvertIpToLong(ip.GetAddressBytes());
            parm.ip = (uint) System.Net.IPAddress.HostToNetworkOrder(iplong);
            parm.port = 5225;
            parm.callback = _callback;

            NativeMethods.HWCtrlLinkConnect(parm);
        }

        public bool SyncTime(DateTime time)
        {
            
            var parm = new tagHWCtrlDeviceTime();
            parm.year = (ushort)time.Year;
            parm.month = (ushort)time.Month;
            parm.day = (ushort)time.Day;
            parm.hour = (ushort)time.Hour;
            parm.minute = (ushort)time.Minute;
            parm.second = (ushort)time.Second;

            var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(parm));
            Marshal.StructureToPtr(parm, ptr, true);

            return NativeMethods.HWCtrlLinkCommand(tagHWCtrlCommand.HWCTRL_COMMAND_UPDATE_TIME, ptr, IntPtr.Zero, 50);
        }

        public DateTime ReadTime()
        {
            var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof (tagHWCtrlDeviceTime)));
            var result = NativeMethods.HWCtrlLinkCommand(tagHWCtrlCommand.HWCTRL_COMMAND_GET_TIME, ptr, IntPtr.Zero, 500);
            var time = (tagHWCtrlDeviceTime) Marshal.PtrToStructure(ptr, typeof (tagHWCtrlDeviceTime));
            Marshal.FreeHGlobal(ptr);
            return  new DateTime(time.year, time.month, time.day, time.hour, time.minute, time.second);
        }

        private void CallBack(tagHWCtrlEvent args)
        {
            this.OnStatusReport(new ControlEventArgs { EventArgs = args });
        }

        public void Dispose()
        {
            //NativeMethods.HWCtrlLinkClose();
        }
    }
}
